package com.shujushow.chapter04.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.Map;

/**
 * Created by xinshu on 2016/4/11.
 */
@Controller
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Value(value = "${application.message}")
    private String message;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginInit(Map<String, Object> model) {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Map<String, Object> model, @RequestParam("userid") String userId,
                        @RequestParam("password") String password) {

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userId, password);

        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException uae) {
            logger.info("未知账户");
        } catch (IncorrectCredentialsException ice) {
            logger.info("密码不正确");
        } catch (LockedAccountException lae) {
            logger.info("账户已锁定");
        } catch (ExcessiveAttemptsException eae) {
            logger.info("用户名密码次数过多");
        } catch (AuthenticationException ae) {
            logger.info("用户名密码不正确");
        }

        if (subject.isAuthenticated()) {
            logger.info("登录认证通过");
            model.put("time", new Date());
            model.put("message", this.message);
            return "redirect:/welcome";
        } else {
            usernamePasswordToken.clear();
            return "redirct:/login";
        }
    }

    @RequestMapping(value="/logout", method=RequestMethod.POST)
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }
}
